<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >

      <el-row>
        <el-col>
          <el-form-item label="公司名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入公司名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-160px"
            />
          </el-form-item>
                    <el-form-item label="手机号码" prop="mobile">
                      <el-input
                        v-model="queryParams.mobile"
                        placeholder="请输入手机号码"
                        clearable
                        @keyup.enter="handleQuery"
                        class="!w-160px"
                      />
                    </el-form-item>
          <el-form-item label="合作等级" prop="cooperationDegree">
            <el-select
              v-model="queryParams.cooperationDegree"
              placeholder="请选择"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.DISPATCH_COOPERATION_DEGREE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审批状态" prop="checkState">
            <el-select
              v-model="queryParams.checkState"
              placeholder="请选择审批状态"
              clearable
              class="!w-160px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.ERP_NO_REPEAL_CHECK_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon icon="ep:search" class="mr-5px"/>
              搜索
            </el-button>
          </el-form-item>

          <el-form-item>

            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" class="mr-5px"/>
              重置
            </el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['erp:company:create']"
            >
              <Icon icon="ep:plus" class="mr-5px"/>
              新增
            </el-button>
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['erp:company:export']"
            >
              <Icon icon="ep:download" class="mr-5px"/>
              导出
            </el-button>
          </el-form-item>

        </el-col>

      </el-row>


    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table border v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!--      <el-table-column label="编号" align="center" prop="id"/>-->
      <el-table-column label="公司名称1" prop="name" min-width="200px">
        <template #default="scope">
          <!--    归属省份+归属城市+归属区+名称       -->

          <!--          {{ scope.row.belongProvince }}{{ scope.row.belongCity }}{{ scope.row.belongDistrict }}-->
          <!--          名称在添加时 拼接保存省市区-->
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="商户数" align="center" prop="storeTotal">
        <template #default="scope">
          <el-button @click="handleStoreList(scope.row)" v-if="scope.row.storeTotal"
                     type="text">{{ scope.row.storeTotal }}
          </el-button>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="contact" min-width="200px"/>
      <el-table-column label="手机号" align="center" prop="mobile" min-width="200px"/>
      <el-table-column label="审批状态" align="center" prop="checkState" min-width="180">
        <template #default="scope">
          <div
            :class="['custom-select', { 'priorit1' : scope.row.checkState === 0 || scope.row.checkState === 3,
          'priorit2' : scope.row.checkState === 1 || scope.row.checkState === 4,
          'priorit3' : scope.row.checkState === 2 || scope.row.checkState === 5}]">
            <el-select style="text-align: center;"
                       @change="handleCompanyCheckChange(scope.row)"
                       v-model="scope.row.checkState">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.ERP_NO_REPEAL_CHECK_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="实名默认" align="center" prop="isDefault" min-width="150">
        <template #default="scope">
          <div
            :class="['custom-select', { 'priorit1' : scope.row.isDefault === 0,
          'priorit2' : scope.row.isDefault === 1}]">
            <el-select style="text-align: center;"
                       @change="handleCompanyDefaultChange(scope.row)"
                       v-model="scope.row.isDefault">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.ERP_COMPANY_DEFAULT)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="省份" align="center" prop="belongProvince"/>
      <el-table-column label="城市" align="center" prop="belongCity"/>
      <el-table-column label="区" align="center" prop="belongDistrict"/>
      <el-table-column label="地址" align="center" prop="belongAddress" min-width="200px"/>
      <!--      <el-table-column label="联系电话" align="center" prop="telephone" />-->
      <!--      <el-table-column label="电子邮箱" align="center" prop="email" />-->

      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>

      <el-table-column label="纳税人识别号" align="center" prop="taxNo" min-width="140px"/>
      <!--      <el-table-column label="税率" align="center" prop="taxPercent"/>-->
      <el-table-column label="开户行" align="center" prop="bankName" min-width="120px"/>
      <el-table-column label="开户账号" align="center" prop="bankAccount" min-width="120px"/>
      <el-table-column label="开户地址" align="center" prop="bankAddress" min-width="120px"/>

      <el-table-column label="合作等级" align="center" prop="cooperationDegree" min-width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_COOPERATION_DEGREE"
                    :value="scope.row.cooperationDegree"/>
        </template>
      </el-table-column>

      <!--      <el-table-column label="门店经度" align="center" prop="longitude" />-->
      <!--      <el-table-column label="门店纬度" align="center" prop="latitude" />-->
      <el-table-column label="结算类型" align="center" prop="settleType" min-width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_SETTLE_TYPE" :value="scope.row.settleType"/>
        </template>
      </el-table-column>
      <el-table-column label="是否开票" align="center" prop="hasInvoice" min-width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_HAS_INVOICE" :value="scope.row.hasInvoice"/>
        </template>
      </el-table-column>
      <el-table-column label="开票类型" align="center" prop="invoiceType" min-width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_INVOICE_TYPE" :value="scope.row.invoiceType"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" width="120px" align="center" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:company:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:company:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CompanyForm ref="formRef" @success="getList"/>

  <StoreForm ref="storeFormRef" @success="getStoreList"/>

  <el-dialog :title="storeTitle" v-model="storeVisible" width="60%">
    <el-button
      type="primary"
      plain
      @click="openStoreForm('create')"
      v-hasPermi="['dispatch:store:create']"
      class="mb-2"
    >
      <Icon icon="ep:plus" class="mr-5px"/>
      新增
    </el-button>
    <el-table v-loading="loading" :data="storeList" max-height="500px" :stripe="true" border
              :show-overflow-tooltip="true">
      <el-table-column label="商户名称" prop="name" min-width="200px"/>
      <el-table-column label="联系人" align="center" prop="contact" min-width="150px"/>
      <el-table-column label="手机号" align="center" prop="mobile" min-width="150px"/>
      <el-table-column label="审批状态" align="center" prop="checkState" min-width="150">
        <template #default="scope">
          <div
            :class="['custom-select', { 'priorit1' : scope.row.checkState === 0 || scope.row.checkState === 3,
          'priorit2' : scope.row.checkState === 1 || scope.row.checkState === 4,
          'priorit3' : scope.row.checkState === 2 || scope.row.checkState === 5}]">
            <el-select style="text-align: center;"
                       @change="handleStoreCheckStateChange(scope.row)"
                       v-model="scope.row.checkState">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.ERP_NO_REPEAL_CHECK_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" align="center" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openStoreForm('update', scope.row.id)"
            v-hasPermi="['dispatch:store:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            @click="storeAttendanceItemShow(scope.row)"
            v-hasPermi="['dispatch:store:update']"
          >
            假勤明细
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleStoreDelete(scope.row.id)"
            v-hasPermi="['dispatch:store:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

  </el-dialog>

  <el-dialog :title="storeAttendanceItemTitle" v-model="storeAttendanceItemVisible"
             width="50%">
    <el-table v-loading="loading" :data="storeAttendanceItemList" row-key="id">
      <el-table-column label="序号" align="center" width="60px" prop="id"/>
      <el-table-column label="月份" align="center">
        <template #default="scope">
          <el-date-picker
            class="!w-180px"
            v-if="!scope.row.id"
            v-model="scope.row.month"
            type="month"
            placeholder="选择年月"
            format="YYYY-MM"
            value-format="YYYY-MM"/>
          <span v-else>
                {{ scope.row.month }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="上班时间" align="center">
        <template #default="scope">
          <el-time-picker class="!w-180px" v-if="!scope.row.id"
                          v-model="scope.row.dayWorkingTimeArray" is-range range-separator="至"
                          format="HH:mm"/>
          <span v-else>
            <el-time-picker class="!w-180px" v-if="scope.row.id" disabled
                            v-model="scope.row.dayWorkingTimeArray" is-range range-separator="至"
                            format="HH:mm"/>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="月休息天数" align="center">
        <template #default="scope">
          <el-input-number v-if="!scope.row.id" class="!w-100px" v-model="scope.row.monthRestDays"
                           :min="1" :max="10" placeholder="请输入月休息天数"/>
          <span v-else> {{ scope.row.monthRestDays }} </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150px">
        <template #default="scope">
          <el-button type="primary" size="small" v-if="!scope.row.id"
                     @click.stop="handleSaveMA(scope.row)">保存
          </el-button>
          <el-button type="danger" size="small" v-if="scope.row.id"
                     @click.stop="handleDelMA(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px">
      <el-button type="success" @click="addLineData">添加月份假勤</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import {getStrDictOptions, getIntDictOptions, DICT_TYPE} from '@/utils/dict'
import {dateFormatter} from '@/utils/formatTime'
import download from '@/utils/download'
import {CompanyApi, CompanyVO} from '@/api/erp/company'
import CompanyForm from './CompanyForm.vue'
import StoreForm from './StoreForm.vue'
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import {StoreApi, StoreVO} from "@/api/dispatch/store";
import {StoreAttendanceApi} from "@/api/dispatch/store/attendance";

/** 派单系统 门店 列表 */
defineOptions({name: 'Company'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const storeAttendanceItemVisible = ref(false)
const storeAttendanceItemList = ref([{id: 0, dayWorkingTimeArray: [new Date(), new Date()]}])
const storeAttendanceItemTitle = ref()
const storeAttendanceId = ref()

const storeVisible = ref(false)
const storeList = ref([])
const storeTitle = ref()
const companyId = ref()

const loading = ref(true) // 列表的加载中
const list = ref<CompanyVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  contact: undefined,
  mobile: undefined,
  telephone: undefined,
  email: undefined,
  remark: undefined,
  status: undefined,
  sort: undefined,
  taxNo: undefined,
  taxPercent: undefined,
  bankName: undefined,
  bankAccount: undefined,
  bankAddress: undefined,
  createTime: [],
  cooperationDegree: undefined,
  belongProvince: undefined,
  belongCity: undefined,
  belongDistrict: undefined,
  belongAddress: undefined,
  longitude: undefined,
  latitude: undefined,
  settleType: undefined,
  hasInvoice: undefined,
  invoiceType: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CompanyApi.getCompanyPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleCompanyCheckChange = async (row) => {

  const companyCheckOptions = getIntDictOptions(DICT_TYPE.ERP_NO_REPEAL_CHECK_TYPE);

  for (const key in companyCheckOptions) {
    if (companyCheckOptions[key].value === row.checkState) {

      await ElMessageBox.confirm(
        '员工【' + row.name + '】审批状态是否修改为【' + companyCheckOptions[key].label + '】?',
        '审批状态确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          const loading = ElLoading.service({
            lock: true,
            text: '处理中...',
            background: 'rgba(0, 0, 0, 0.7)',
          })

          try {
            await CompanyApi.updateCompanyCheckState(row.id, row.checkState);
            ElMessage({
              type: 'success',
              message: '审批状态已调整',
            })
          } finally {
            loading.close()
          }
        })
        .catch(() => {
        }).finally(() => {
          getList()
        })
    }
  }
}
const handleCompanyDefaultChange = async (row) => {
  const selectedOptions = getIntDictOptions(DICT_TYPE.ERP_COMPANY_DEFAULT);
  for (const key in selectedOptions) {
    console.log(selectedOptions[key].value)
    if (selectedOptions[key].value === row.isDefault) {
      await ElMessageBox.confirm(
        '公司【' + row.name + '】是否修改为【' + selectedOptions[key].label + '】?',
        '默认公司确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          const loading = ElLoading.service({
            lock: true,
            text: '处理中...',
            background: 'rgba(0, 0, 0, 0.7)',
          })

          try {
            await CompanyApi.updateCompanyDefault(row.id, row.isDefault);
            ElMessage({
              type: 'success',
              message: '默认公司已调整',
            })
          } finally {
            loading.close()
          }
        })
        .catch(() => {
        }).finally(() => {
          getList()
        })
    }
  }
}


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CompanyApi.deleteCompany(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CompanyApi.exportCompany(queryParams)
    download.excel(data, '派单系统 门店.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleStoreList = async (row, type) => {
  let id = row.id;
  companyId.value = id;
  console.log(companyId.value)
  //搜索中 提示
  let loading = ElLoading.service({
    lock: true,
    text: '搜索中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    storeList.value = [];
    if (type == 'today') {
      storeTitle.value = "【" + row.name + "】的所有门店";
    }
    await StoreApi.getStoreList(id).then(res => {
      storeList.value = res;
    })
    storeVisible.value = true;
  } finally {
    loading.close();
  }

}

/** 查询列表 */
const getStoreList = async () => {
  loading.value = true
  try {
    await StoreApi.getStoreList(companyId.value).then(res => {
      storeList.value = res;
    })
  } finally {
    loading.value = false
  }
}

/** 添加/修改操作 */
const storeFormRef = ref()
const openStoreForm = (type: string, id?: number) => {
  if(type ==='create'){
    id = companyId.value;
  }
  console.log(type + "-" +id)
  storeFormRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleStoreDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await StoreApi.deleteStore(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getStoreList()
  } catch {
  }
}


const handleStoreCheckStateChange = async (row) => {

  const storeCheckOptions = getIntDictOptions(DICT_TYPE.ERP_NO_REPEAL_CHECK_TYPE);

  for (const key in storeCheckOptions) {
    if (storeCheckOptions[key].value === row.checkState) {

      await ElMessageBox.confirm(
        '商户【' + row.name + '】审批状态是否修改为【' + storeCheckOptions[key].label + '】?',
        '审批状态确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          const loading = ElLoading.service({
            lock: true,
            text: '处理中...',
            background: 'rgba(0, 0, 0, 0.7)',
          })

          try {
            await StoreApi.updateStoreCheckState(row.id, row.checkState);
            ElMessage({
              type: 'success',
              message: '审批状态已调整',
            })
          } finally {
            loading.close()
          }
        })
        .catch(() => {
        }).finally(() => {
          getStoreList()
        })
    }
  }

}


const storeAttendanceSubmit = async () => {
  let id = storeAttendanceId.value;

  //搜索中 提示
  let loading = ElLoading.service({
    lock: true,
    text: '搜索中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    await StoreAttendanceApi.getStoreAttendanceList(id).then(res => {
      storeAttendanceItemList.value = res;
    })
  } finally {
    loading.close();
  }

}

const addLineData = async (row) => {
  const newData = {
    month: '1',
    monthRestDays: 1,
    dayWorkingTimeArray: []
  };
  storeAttendanceItemList.value.push(newData);
}

const handleSaveMA = async (row) => {
  ElMessageBox.confirm("确认保存该条数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    row.storeId = storeAttendanceId.value;
    row.sort = 0;
    StoreAttendanceApi.createStoreAttendance(row)
    message.success(t('common.createSuccess'))
  }).catch(() => {
  }).finally(() => {
    storeAttendanceSubmit();
  });
}

const handleDelMA = async (row) => {
  ElMessageBox.confirm("确认删除该条数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    StoreAttendanceApi.deleteStoreAttendance(row.id)
    message.success(t('common.delSuccess'))
    storeAttendanceSubmit();
  });

}

const storeAttendanceItemShow = async (row) => {
  storeAttendanceItemTitle.value = "【" + row.name + "】假勤设置明细";
  storeAttendanceItemVisible.value = true;
  storeAttendanceId.value = row.id;
  storeAttendanceSubmit();
}

/** 初始化 **/
onMounted(() => {
  getList();
})
const route = useRoute();
onActivated(() => {
  //快捷添加
  let query = route.query;
  if (query.doType == 'handAdd') {
    formRef.value.open("create");
  }
  getList();
});

</script>
